using System;
using UnityEngine;
using UnityEngine.UI;
using Utility.GameEvents.Core;
using Utility.GameEvents.Examples;

namespace Utility.GameEvents.Examples {
    public class GameManager : MonoBehaviour, IGameEventListener<EnemyDefeatedEvent>,
        IGameEventListener<GamePausedEvent>, IGameEventListener<GameResumedEvent> {
        private int _totalScore = 0;
        private bool _isPaused = false;
        
		[SerializeField, Utility.Attributes.NotNull] private Text m_toggleText;

        public bool IsPaused => _isPaused;

        private void OnEnable() {
            EventBus.Register<EnemyDefeatedEvent>(this);
            EventBus.Register<GamePausedEvent>(this);
            EventBus.Register<GameResumedEvent>(this);
        }

        private void OnDisable() {
            EventBus.Unregister<EnemyDefeatedEvent>(this);
            EventBus.Unregister<GamePausedEvent>(this);
            EventBus.Unregister<GameResumedEvent>(this);
        }
        
        public void OnEventRaised(EnemyDefeatedEvent gameEvent) {
            _totalScore += gameEvent.PointsAwarded;
            EventBus.Raise(new PlayerScoreChangedEvent("SystemOverall", _totalScore, gameEvent.PointsAwarded));
        }

        public void OnEventRaised(GamePausedEvent gameEvent) {
            if(_isPaused) return;
            _isPaused = true;
            Time.timeScale = 0f;
            
            m_toggleText.text = "Resume?";
        }

        public void OnEventRaised(GameResumedEvent gameEvent) {
            if(!_isPaused) return;
            _isPaused = false;
            Time.timeScale = 1f;
            m_toggleText.text = "Paused?";
        }

        public void RequestTogglePause() {
            if (_isPaused) {
                EventBus.Raise(new GameResumedEvent());
            }
            else {
                EventBus.Raise(new GamePausedEvent());
                
            }
        }
    }
}